<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
function curl_post($url, $post)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}

function curl_get($url, $param = array())
{
    //初始化
    $ch = curl_init();
    //设置选项，包括URL
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    if (isset($param['max_wait_time'])) {
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $param['max_wait_time']);
    }
    //执行并获取HTML文档内容
    $output = curl_exec($ch);
    //释放curl句柄
    curl_close($ch);
    return $output;
}

/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean $adv 是否进行高级模式获取（有可能被伪装）
 * @return mixed
 */
function get_client_ip($type = 0, $adv = false)
{
    $type = $type ? 1 : 0;
    static $ip = NULL;
    if ($ip !== NULL) return $ip[$type];
    if ($adv) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos) unset($arr[$pos]);
            $ip = trim($arr[0]);
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

/**
 * get_encrypt:get the encrypt
 * get the encrypt password
 * @param  integer $num
 * @return string $encrypt
 */
function get_encrypt($num = 6, $numc = false)
{
    $str = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    $w = 61;
    if ($numc) {
        $str = '1234567890';
        $w = 9;
    }
    $encrypt = '';
    for ($i = 0; $i < $num; $i++) {
        $encrypt .= $str{mt_rand(0, $w)};
    }
    return $encrypt;
}

//过滤微信昵称中的不识别表情符号
function clwechatname($nickname)
{
    $nickname = json_encode(array($nickname));
    $nickname = preg_replace("/\\\ud8[3|4]c\\\ud[c|d|f][a-zA-Z0-9]{2}/", "", $nickname);
    $nickname = json_decode($nickname, true);
    return $nickname[0];
}

if (!function_exists('rm')) {
    function rm($status, $info, $data = '')
    {
        $data === null ? $data = "" : $data = $data;
        return array(
            'status' => $status,
            'info' => $info,
            'data' => $data
        );
    }
}


//检测是否是手机号
function check_mobile($str)
{
    $pattern = "/^(1)\d{10}$/";//手机号码
    if (preg_match($pattern, $str)) {
        Return true;
    } else {
        Return false;
    }
}

//过滤单双引号
function replace_dsyh($value)
{
    if (is_array($value)) {
        foreach ($value as $key => $val) {
            $value[$key] = htmlspecialchars($val, ENT_QUOTES);//html实体转换
        }
    } else {
        $value = htmlspecialchars($value, ENT_QUOTES);//html实体转换
    }
    return $value;
}

function GetDistance($lat1, $lng1, $lat2, $lng2)
{
    $EARTH_RADIUS = 6378.137;
    $radLat1 = rad($lat1);
    $radLat2 = rad($lat2);
    $a = $radLat1 - $radLat2;
    $b = rad($lng1) - rad($lng2);
    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) +
            cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
    $s = $s * $EARTH_RADIUS;
//    $s = round($s * 10000) / 10000;
    $s = round(round($s * 10000) / 10000,1);
    return $s;
}

function rad($d)
{
    return $d * 3.1415926535898 / 180.0;
}

function check_is_time($time)
{
    $preg = '/^([0-1]\d|2[0-4]):([0-5]\d)(:[0-5]\d)?$/';
    return preg_match($preg, $time, $match) > 0 ? true : false;
}

/**
 * 地址:https://github.com/PHPOffice/PHPExcel    下载PHPExcel，下载后只需要Classes目录下的文件即可。
 * 数据导出
 * @param array $title 标题行名称
 * @param array $data 导出数据
 * @param string $fileName 文件名
 * @param string $savePath 保存路径
 * @param $type   是否下载  false--保存   true--下载
 * @return string   返回文件全路径
 */
function exportExcel($title = array(), $data = array(), $fileName = '', $sheet = '', $savePath = './', $isDown = false)
{
    \think\Loader::import('phpexcel.PHPExcel');
    \think\Loader::import('phpexcel.PHPExcel.IOFactory');
    $obj = new \PHPExcel();

    //横向单元格标识
    $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');

    $obj->getActiveSheet(0)->setTitle($sheet);   //设置sheet名称
    $_row = 1;   //设置纵向单元格标识
    if ($title) {
        $_cnt = count($title);
        // $obj->getActiveSheet(0)->mergeCells('A'.$_row.':'.$cellName[$_cnt-1].$_row);   //合并单元格
        // $obj->setActiveSheetIndex(0)->setCellValue('A'.$_row, '数据导出：'.date('Y-m-d H:i:s'));  //设置合并后的单元格内容
        // $_row++;
        $i = 0;
        foreach ($title AS $v) {   //设置列标题
            $obj->setActiveSheetIndex(0)->setCellValue($cellName[$i] . $_row, $v);
            $i++;
        }
        $_row++;
    }

    //填写数据
    if ($data) {
        $i = 0;
        foreach ($data AS $_v) {
            $j = 0;
            foreach ($_v AS $_cell) {
                $obj->getActiveSheet(0)->setCellValue($cellName[$j] . ($i + $_row), $_cell);
                $j++;
            }
            $i++;
        }
    }

    //文件名处理
    if (!$fileName) {
        $fileName = uniqid(time(), true);
    }

    $objWrite = \PHPExcel_IOFactory::createWriter($obj, 'Excel2007');


    if ($isDown) {   //网页下载
        header('pragma:public');
        header("Content-Disposition:attachment;filename=$fileName.xlsx");
        $objWrite->save('php://output');
        exit;
    }

    $_fileName = iconv("utf-8", "gb2312", $fileName);   //转码
    $_savePath = $savePath . $_fileName . '.xlsx';
    $objWrite->save($_savePath);

    return $savePath . $fileName . '.xlsx';
}

function httpdownload($showname = '', $content = '', $expire = 180)
{
    if ($content != '') {
        $length = strlen($content);
    } else {
        echo '下载文件不存在';
        exit;
    }
    if (empty($showname)) {
        $showname = 'download';
    }
    $showname = basename($showname);
    $type = "application/octet-stream";

    header("Pragma: public");
    header("Cache-control: max-age=" . $expire);
    header("Expires: " . gmdate("D, d M Y H:i:s", time() + $expire) . "GMT");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . "GMT");
    header("Content-Disposition: attachment; filename=" . $showname);
    header("Content-Length: " . $length);
    header("Content-type: " . $type);
    header('Content-Encoding: none');
    header("Content-Transfer-Encoding: binary");
    echo($content);
    exit();
}


//判断是否是正确的邮箱格式;
function isEmail($email)
{
    $mode = '/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/';
    if (preg_match($mode, $email)) {
        return true;
    } else {
        return false;
    }
}


function sthtml($value)
{
    $v = htmlspecialchars_decode($value);
    return strip_tags($v);
}

/**
 * GET 请求
 * @param string $url
 */
function http_get($url)
{
    $oCurl = curl_init();
    if (stripos($url, "https://") !== FALSE) {
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
    }
    curl_setopt($oCurl, CURLOPT_URL, $url);
    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
    $sContent = curl_exec($oCurl);
    $aStatus = curl_getinfo($oCurl);
    curl_close($oCurl);
    if (intval($aStatus["http_code"]) == 200) {
        return $sContent;
    } else {
        return false;
    }
}


function http_post($url, $param, $post_file = false)
{
    $oCurl = curl_init();
    if (stripos($url, "https://") !== FALSE) {
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
    }
    if (is_string($param) || $post_file) {
        $strPOST = $param;
    } else {
        $aPOST = array();
        foreach ($param as $key => $val) {
            if (empty($val)) continue;
            $aPOST[] = $key . "=" . urlencode($val);
        }
        $strPOST = join("&", $aPOST);
    }
    curl_setopt($oCurl, CURLOPT_URL, $url);
    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($oCurl, CURLOPT_POST, true);
    curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
    $sContent = curl_exec($oCurl);
    $aStatus = curl_getinfo($oCurl);
    curl_close($oCurl);
    if (intval($aStatus["http_code"]) == 200) {
        return $sContent;
    } else {
        return false;
    }
}

/**
 * 微信api不支持中文转义的json结构
 * @param array $arr
 */
function _json_encode($arr)
{
    $parts = array();
    $is_list = false;
    //Find out if the given array is a numerical array
    $keys = array_keys($arr);
    $max_length = count($arr) - 1;
    if (($keys [0] === 0) && ($keys [$max_length] === $max_length)) { //See if the first key is 0 and last key is length - 1
        $is_list = true;
        for ($i = 0; $i < count($keys); $i++) { //See if each key correspondes to its position
            if ($i != $keys [$i]) { //A key fails at position check.
                $is_list = false; //It is an associative array.
                break;
            }
        }
    }
    foreach ($arr as $key => $value) {
        if (is_array($value)) { //Custom handling for arrays
            if ($is_list)
                $parts [] = _json_encode($value); /* :RECURSION: */
            else
                $parts [] = '"' . $key . '":' . _json_encode($value); /* :RECURSION: */
        } else {
            $str = '';
            if (!$is_list)
                $str = '"' . $key . '":';
            //Custom handling for multiple data types
            if (!is_string($value) && is_numeric($value) && $value < 2000000000)
                $str .= $value; //Numbers
            elseif ($value === false)
                $str .= 'false'; //The booleans
            elseif ($value === true)
                $str .= 'true';
            else
                $str .= '"' . addslashes($value) . '"'; //All other things
            // :TODO: Is there any more datatype we should be in the lookout for? (Object?)
            $parts [] = $str;
        }
    }
    $json = implode(',', $parts);
    if ($is_list)
        return '[' . $json . ']'; //Return numerical JSON
    return '{' . $json . '}'; //Return associative JSON
}


function is_mobile()
{
    $user_agent = $_SERVER['HTTP_USER_AGENT'];

    $mobile_agents = Array("240x320", "acer", "acoon", "acs-", "abacho", "ahong", "airness", "alcatel", "amoi", "android", "anywhereyougo.com", "applewebkit/525", "applewebkit/532", "asus", "audio", "au-mic", "avantogo", "becker", "benq", "bilbo", "bird", "blackberry", "blazer", "bleu", "cdm-", "compal", "coolpad", "danger", "dbtel", "dopod", "elaine", "eric", "etouch", "fly ", "fly_", "fly-", "go.web", "goodaccess", "gradiente", "grundig", "haier", "hedy", "hitachi", "htc", "huawei", "hutchison", "inno", "ipad", "ipaq", "ipod", "jbrowser", "kddi", "kgt", "kwc", "lenovo", "lg ", "lg2", "lg3", "lg4", "lg5", "lg7", "lg8", "lg9", "lg-", "lge-", "lge9", "longcos", "maemo", "mercator", "meridian", "micromax", "midp", "mini", "mitsu", "mmm", "mmp", "mobi", "mot-", "moto", "nec-", "netfront", "newgen", "nexian", "nf-browser", "nintendo", "nitro", "nokia", "nook", "novarra", "obigo", "palm", "panasonic", "pantech", "philips", "phone", "pg-", "playstation", "pocket", "pt-", "qc-", "qtek", "rover", "sagem", "sama", "samu", "sanyo", "samsung", "sch-", "scooter", "sec-", "sendo", "sgh-", "sharp", "siemens", "sie-", "softbank", "sony", "spice", "sprint", "spv", "symbian", "tablet", "talkabout", "tcl-", "teleca", "telit", "tianyu", "tim-", "toshiba", "tsm", "up.browser", "utec", "utstar", "verykool", "virgin", "vk-", "voda", "voxtel", "vx", "wap", "wellco", "wig browser", "wii", "windows ce", "wireless", "xda", "xde", "zte");
    $is_mobile = false;
    foreach ($mobile_agents as $device) {//这里把值遍历一遍，用于查找是否有上述字符串出现过
        if (stristr($user_agent, $device)) { //stristr 查找访客端信息是否在上述数组中，不存在即为PC端。
            $is_mobile = true;
            break;
        }
    }
    return $is_mobile;
}

function get_img_type($url)
{
    $id = exif_imagetype($url);
    switch ($id) {
        case 1:
            $return = 'gif';
            break;
        case 2:
            $return = 'jpg';
            break;
        case 3:
            $return = 'png';
            break;
        default:
            $return = false;
            break;
    }
    return $return;
}

function unicodeDecode($unicode_str)
{
    $json = '{"str":"' . $unicode_str . '"}';
    $arr = json_decode($json, true);
    if (empty($arr)) return '';
    return $arr['str'];
}

if (!function_exists('__')) {

    /**
     * 获取语言变量值
     * @param string $name 语言变量名
     * @param array $vars 动态变量值
     * @param string $lang 语言
     * @return mixed
     */
    function __($name, $vars = [], $lang = '')
    {
        if (is_numeric($name) || !$name)
            return $name;
        if (!is_array($vars)) {
            $vars = func_get_args();
            array_shift($vars);
            $lang = '';
        }
        return \think\Lang::get($name, $vars, $lang);
    }

}

/** 根据生日计算年龄
 * @param $birthday 2018-01-01
 * @return false|string
 */
function get_age($birthday)
{
    $birthday = strtotime($birthday);
    //格式化出生时间年月日
    $byear = date('Y', $birthday);
    $bmonth = date('m', $birthday);
    $bday = date('d', $birthday);
    //格式化当前时间年月日
    $tyear = date('Y');
    $tmonth = date('m');
    $tday = date('d');
    //开始计算年龄
    $age = $tyear - $byear;
    if ($age > 0 && ($bmonth > $tmonth || $bmonth == $tmonth && $bday > $tday)) {
        $age--;
    }
    return $age;
}

/**
 * 用户数据处理，将数值表示的用户信息字段转换为字符
 * @param $user
 * @return mixed
 */
function userInfoDeal($user)
{
    $education = [0 => '未知', 1 => '高中', 2 => '中专', 3 => '大专', 4 => '本科', 5 => '硕士', 6 => '博士', 7 => '博士后'];
    $work = [0 => '未知', 1 => '国企', 2 => '外商独资', 3 => '合资', 4 => '民营', 5 => '股份制企业', 6 => '上市公司', 7 => '国家机关', 8 => '事业单位', 9 => '银行', 10 => '医院', 11 => '学校', 12 => '律师事务所', 13 => '社会团体', 14 => '港澳台公司', 15 => '其他'];
    $property = [0 => '未知', 1 => '无房', 2 => '1套房', 3 => '2套房', 4 => '3套及以上', 5 => '其他'];
    $income = [0 => '未知', 1 => '3000以下', 2 => '3001-5000', 3 => '5001-8000', 4 => '8001-12000', 5 => '12001-20000', 6 => '200001-50000', 7 => '50000以上'];
    $marriage = [0 => '未知', 1 => '未婚', 2 => '离异', 3 => '丧偶'];
    $has_car = [0 => '未知', 1 => '是', 2 => '否'];
    $has_child = [0 => '未知', 1 => '是', 2 => '否'];
    // 百分百转数组
    $user = json_decode(json_encode($user), true);
    if (count($user) == 0) {
        return [];
    }
    if (isset($user[0])) {
        // 二维数组
        foreach ($user as $key => $value) {
            if ($value['gender'] == 1) {
                $user[$key]['gender'] = '男';
            } elseif ($value['gender'] == 2) {
                $user[$key]['gender'] = '女';
            } else {
                $user[$key]['gender'] = '未知';
            }
            if (isset($value['education'])) $user[$key]['education'] = $education[$value['education']];
            if (isset($value['work'])) $user[$key]['work'] = $work[$value['work']];
            if (isset($value['property'])) $user[$key]['property'] = $property[$value['property']];
            if (isset($value['income'])) $user[$key]['income'] = $income[$value['income']];
            if (isset($value['marriage'])) $user[$key]['marriage'] = $marriage[$value['marriage']];
            if (isset($value['has_car'])) $user[$key]['has_car'] = $has_car[$value['has_car']];
            if (isset($value['has_child'])) $user[$key]['has_child'] = $has_child[$value['has_child']];
        }
        unset($value);
    } else {
        // 一维数组
        if (isset($user['gender'])) {
            if ($user['gender'] == 1) {
                $user['gender'] = '男';
            } elseif ($user['gender'] == 2) {
                $user['gender'] = '女';
            } else {
                $user['gender'] = '未知';
            }
        }

        if (isset($user['education'])) $user['education'] = $education[$user['education']];
        if (isset($user['work'])) $user['work'] = $work[$user['work']];
        if (isset($user['property'])) $user['property'] = $property[$user['property']];
        if (isset($user['income'])) $user['income'] = $income[$user['income']];
        if (isset($user['marriage'])) $user['marriage'] = $marriage[$user['marriage']];
        if (isset($user['has_car'])) $user['has_car'] = $has_car[$user['has_car']];
        if (isset($user['has_child'])) $user['has_child'] = $has_child[$user['has_child']];
    }
    return $user;
}

function lastLogin($time)
{
    $diff = time() - (int)$time;
    $res = $diff / 60 / 60;
    return round($res, 1);
}

/**
 * 获取全球唯一标识
 * @return string
 */
function uuid()
{
    return sprintf(
        '%04x%04x-%04x-%04x-%04x-%04x%04x%04x', mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0x0fff) | 0x4000, mt_rand(0, 0x3fff) | 0x8000, mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
    );
}

/**
 * 输出数组打印调试
 */
function toArrayDebug($string)
{
    halt(json_decode(json_encode($string), true));
}

/**
 * 实现array_column函数
 */

function column_array(array &$rows, $column_key, $index_key = null)
{
    $data = array();
    if (empty($index_key)) {
        foreach ($rows as $row) {
            $data[] = $row[$column_key];
        }
    } else {
        foreach ($rows as $row) {
            $data[$row[$index_key]] = $row[$column_key];
        }
    }
    return $data;
}

